package com.ccteam.shared.domain.user

import com.ccteam.model.Resource
import com.ccteam.network.ApiError
import com.ccteam.shared.data.user.UserRepository
import com.ccteam.shared.domain.FlowUseCase
import com.ccteam.shared.result.user.UserInfoEditInfo
import com.ccteam.shared.utils.EMPTY_STRING
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/20
 *
 * 个人信息获取Domain层
 */
class SelfInformationDataUseCase @Inject constructor(
    private val userRepository: UserRepository
): FlowUseCase<String?, UserInfoEditInfo>(
    Dispatchers.IO
) {
    override fun execute(parameters: String?): Flow<Resource<UserInfoEditInfo>> {
        if(parameters.isNullOrEmpty()){
            return flowOf(Resource.Error(ApiError.unknownCode,"用户操作非法"))
        }
        return userRepository.getUserInfo(parameters).map {
            when (it) {
                is Resource.Success -> {
                    if(!it.data.isNullOrEmpty()){
                        Resource.Success(
                            UserInfoEditInfo(
                                it.data!![0].id,
                                it.data!![0].name,
                                it.data!![0].introduction ?: EMPTY_STRING,
                                it.data!![0].birthday ?: EMPTY_STRING,
                                it.data!![0].gender,
                                it.data!![0].photoUrl ?: EMPTY_STRING
                            )
                        )
                    } else {
                        Resource.Error(ApiError.unknownCode,"用户信息不存在")
                    }
                }
                is Resource.Loading -> {
                    Resource.Loading(null)
                }
                else -> {
                    Resource.Error(it.errorCode,it.message ?: "未知错误",null)
                }
            }
        }
    }
}